package ru.reaperoq.inventory.screens.main.admin.users

import LoadingStatus
import UserAdminViewModel
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AdminPanelSettings
import androidx.compose.material.icons.filled.LocationCity
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import models.admin.AdminEvent
import models.shared.UserUi
import org.koin.androidx.compose.navigation.koinNavViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UsersScreen(modifier: Modifier = Modifier, viewModel: UserAdminViewModel = koinNavViewModel()) {
    val viewState by viewModel.viewStates().collectAsState()
    var showChangeRoleDialog by remember { mutableStateOf(false) }
    var showChangeLocationDialog by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        viewModel.obtainEvent(AdminEvent.LoadUsers)
    }

    if (showChangeRoleDialog && viewState.selectedUser != null) {
        ChangeUserRoleDialog(
            userUi = viewState.selectedUser!!,
            onDismiss = { showChangeRoleDialog = false }) { id, role ->
            viewModel.obtainEvent(AdminEvent.UpdateRole(id, role))
            showChangeRoleDialog = false
        }
    }

    if (showChangeLocationDialog && viewState.selectedUser != null) {
        ChangeUserLocationDialog(
            user = viewState.selectedUser!!,
            locations = viewState.locations,
            onDismissRequest = { showChangeLocationDialog = false },
            onConfirm = { id, locId ->
                viewModel.obtainEvent(AdminEvent.UpdateLocation(id, locId))
                showChangeLocationDialog = false
            }
        )
    }

    Scaffold(
        modifier = modifier,
        topBar = {
            CenterAlignedTopAppBar(title = { Text(text = "Пользователи") })
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .consumeWindowInsets(padding)
                .padding(padding)
                .fillMaxWidth()
        ) {
            if (viewState.loadingStatus is LoadingStatus.Loading) {
                LinearProgressIndicator(Modifier.fillMaxWidth())
            }
            UsersList(
                users = viewState.users,
                onEditRoleClick = {
                    viewModel.obtainEvent(AdminEvent.SelectUser(it))
                    showChangeRoleDialog = true
                },
                onEditLocationClick = {
                    viewModel.obtainEvent(AdminEvent.SelectUser(it))
                    showChangeLocationDialog = true
                }
            )
        }
    }
}

@Composable
fun UsersList(
    modifier: Modifier = Modifier,
    users: List<UserUi>, onEditRoleClick: (UserUi) -> Unit, onEditLocationClick: (UserUi) -> Unit
) {
    LazyColumn(
        modifier = modifier
    ) {
        items(users, key = { it.id }) {
            UserItem(
                user = it,
                onEditRoleClick = { onEditRoleClick(it) },
                onEditLocationClick = { onEditLocationClick(it) }
            )
        }
    }
}

@Composable
fun UserItem(
    modifier: Modifier = Modifier,
    user: UserUi,
    onEditRoleClick: () -> Unit,
    onEditLocationClick: () -> Unit
) {
    val textColor = if (user.location != null) {
        MaterialTheme.colorScheme.primary
    } else {
        MaterialTheme.colorScheme.error
    }
    val role = remember(user) {
        when (user.role) {
            UserUi.Role.USER -> "Пользователь"
            UserUi.Role.MODERATOR -> "Модератор"
            UserUi.Role.ADMIN -> "Администратор"
        }
    }
    ListItem(
        modifier = modifier,
        headlineContent = { Text(user.username) },
        supportingContent = {
            Text(
                buildAnnotatedString {
                    append(role)
                    withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
                        append(" • ")
                    }
                    withStyle(style = SpanStyle(color = textColor)) {
                        append(user.location?.name ?: "Без локации")
                    }
                }
            )
        },
        trailingContent = {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(onClick = onEditRoleClick) {
                    Icon(imageVector = Icons.Default.AdminPanelSettings, contentDescription = null)
                }
                IconButton(onClick = onEditLocationClick) {
                    Icon(imageVector = Icons.Default.LocationCity, contentDescription = null)
                }
            }
        }
    )
}